// index.js
// 获取应用实例
const app = getApp()
// let token = wx.getStorageSync("token")
// let user_id = wx.getStorageSync("user_id")


Page({
  data: {
    scale: 1, // 缩放比例
    lastScale: 1, // 上一次的缩放比例
    distance: 0, // 双指间距离
    lastDistance: 0, // 上一次双指间距离
    touches: [], // 触摸点数组
    treeData: [],
    showPopBox: false,
    array: [1,2,3,4,5],
    name: '张晓明',
    popboxData: {
        boxStatus: false,
        addNode: false
    },
    currentNodeData: {},
    currentParents: [],
    currentChildren: [],
    nodeWidth: 2,
    nodeHeight: 5,
    nodeMargin: 0.5,
    nodeFontSize: 12,
    nodeStyle: '',
    personItemStyle: {},
    personItemHeight: 7.7,
    personCount: [],
    personCount2: [],
    total: {
        all: 0,
        male: 0,
        female: 0
    },
    dictNumber: ['一','二','三','四','五','六','七','八','九'],
    sideBar: true,
    sideBarTxt: '收起',
    familyId: ''
  },
  onLoad(options) {
    app.globalData.familyId = options.familyId
  },
  onShow() {
    app.globalData.home = this
    let token = wx.getStorageSync("token")
    if(token) this.getFamilyData(token)
  },
  //引入的tree组件事件处理函数
  tapItem: function (e) {
    this.setData({ 
        popboxData: { boxStatus: true }, 
        currentNodeData: e.detail.item,
        currentParents: e.detail.parents,
        currentChildren: e.detail.children
    })
  },
  //点击出现弹窗
  tapItemFather: function(e) {
    var item = e.currentTarget.dataset.item;
    this.setData({ 
        popboxData: { boxStatus: true }, 
        currentNodeData: item,
        currentParents: []
    })
  },
  //获取家族成员列表
  getFamilyData(token){
    let this_ = this
    wx.request({
        url: app.globalData.url + '/ft-family/member?id=1', 
        method: 'GET',
        header: {
            'content-type': 'application/json',
            'cookie': 'token=' + token,
        },
        success (res) {
            this_.setData({ treeData: res.data.data})
            this_.countPersonSex(res.data.data, 0)
            this_.setData({ personCount2: this_.data.personCount })
            this_.countTotalPerson(this_.data.personCount)
            this_.setData({ personCount: [] })
        }
    })
  },
  //绑定家族ID
  bindUserToFamily(familyId) {
    wx.request({
        url: app.globalData.url + '/ft-user/bind-family', 
        method: 'POST',
        header: {
            'content-type': 'application/json',
            'cookie': 'token=' + wx.getStorageSync("token"),
        },
        data: {
            family_id: familyId
        },
        success (res) {
            if(res.statusCode == 200) {
                console.log(res)
            }
        }
    })
  },
  //显示弹窗
  showPop() {
    this.setData({ popboxData:{ boxStatus: true }})
  },
  //隐藏弹窗
  closePop() {
    this.setData({ popboxData:{ boxStatus: false }})
  },
  //放大节点
  larger() {
    let d =  this.data
    if(d.nodeWidth >= 2) return
    d.nodeWidth += 0.2,
    d.nodeHeight += 0.5,
    d.nodeMargin += 0.1,
    d.nodeFontSize += 2,
    d.personItemHeight += 1.5
    this.setData({ 
        nodeStyle: 'width:'+ d.nodeWidth + 'em;'+'height:'+ d.nodeHeight + 'em;' + 'margin:0 '+ d.nodeMargin +'em '+ d.nodeMargin + ' em;' + 'font-size:' + d.nodeFontSize + 'px',
        personItemStyle: 'height:' +d.personItemHeight + 'em'
    })
  },
  //缩小节点
  smaller() {
    let d =  this.data
    if(d.nodeWidth <= 1.6) return
    d.nodeWidth -= 0.2,
    d.nodeHeight -= 0.5,
    d.nodeMargin -= 0.1,
    d.nodeFontSize -= 2,
    d.personItemHeight -= 1.5
    this.setData({ 
        nodeStyle: 'width:'+ d.nodeWidth + 'em;'+'height:'+ d.nodeHeight + 'em;' + 'margin:0 '+ d.nodeMargin +'em '+ d.nodeMargin + ' em;' + 'font-size:' + d.nodeFontSize + 'px',
        personItemStyle: 'height:' +d.personItemHeight + 'em'
    })
  },
  //收起/展开左侧
  toggerSide(e) {
    wx.removeStorage({ key: 'token', success: function(res) { console.log(res.data) } })
    // this.data.sideBar ? this.setData({ sideBar: false, sideBarTxt: '展开' }) : this.setData({ sideBar: true, sideBarTxt: '收起' })
  },
  
  //添加节点
  addNode(e) {
      let d = this.data.currentNodeData
      d.ft_level += 1
      let params = 'relation_id='+d.id+
        '&sex='+e.target.dataset.num[0]+
        '&relation_type='+e.target.dataset.num[1]+
        '&family_id='+d.family_id+
        '&ft_level='+d.ft_level
      wx.navigateTo({
        url: '../add/index?' + params
      })
  },
  //编辑节点
  updateNode(e) {
    let d = this.data.currentNodeData
    let params = 'id='+d.id
    wx.navigateTo({
      url: '../edit/index?' + params
    })
  },
  //查看节点
  queryNode(e) {
    let d = this.data.currentNodeData
    let params = 'id='+d.id
    wx.navigateTo({
      url: '../query/index?' + params
    })
  },
  //删除节点
  deleteNode() {
      let id = this.data.currentNodeData.id
      let this_ = this
      wx.request({
        url: app.globalData.url + '/ft-person/delete?id=' + id, 
        method: 'GET',
        header: {
            'content-type': 'application/json',
            'cookie': wx.getStorageSync("sessionid")
        },
        success (res) {
            if(res.statusCode == 200) {
                this_.setData({ popboxData:{ boxStatus: false }})
                this_.getFamilyData()
            }
        }
    })
  },
  //调整排行
  adjustNode(e) {
    let d = this.data.currentNodeData
    let a = JSON.stringify(this.data.currentChildren)
    let params = 'children='+a+'&id='+d.id+'&relationId='+d.relation_id
    wx.navigateTo({
      url: '../adjust/index?' + params
    })
  },
  //查找父母
  findParents(id, level) {
    this.data.treeData
  },
  //统计男女数量
  countPersonSex(data, level) {
    if( !this.data.personCount[level]) this.data.personCount[level] = [0,0]
    data.forEach((item,index)=>{
        item.parents.forEach((m,i)=>{
            // console.log(m.name)
            m.sex==1 ? this.data.personCount[level][0] +=1 : this.data.personCount[level][1] +=1   
        })
        if(item.children.length>0) {
            this.countPersonSex(item.children, level+1)
        }
    })
    // console.log(this.data.personCount)
  },
  //统计总人数
  countTotalPerson(arr) {
    let male = 0, female = 0, all = 0
    arr.forEach(item=>{
        male += item[0]
        female += item[1]
        all += (item[0] + item[1])
    })
    this.setData({ total: { male, female, all } })
  },
  // 触摸开始  
  handleTouchStart: function(e) {  
    if (e.touches.length === 2) {  
      this.setData({  
        touches: [e.touches[0], e.touches[1]],  
        lastDistance: this.getDistance(e.touches[0], e.touches[1]),  
        lastScale: this.data.scale  
      });  
    }  
  },  
  // 触摸移动  
  handleTouchMove: function(e) {  
    if (e.touches.length === 2) {
      const distance = this.getDistance(e.touches[0], e.touches[1]);  
      const scale = this.data.lastScale * (distance / this.data.lastDistance);  
      // 限制缩放范围  
      if (scale > 0.5 && scale < 2) {  
        this.setData({  
          scale: scale,  
          distance: distance  
        });  
      }  
    }  
  },  
  // 触摸结束  
  handleTouchEnd: function() {  
    this.setData({  
      touches: []  
    });  
  },  
  // 计算两点间距离  
  getDistance: function(touch1, touch2) {  
    const dx = touch1.clientX - touch2.clientX;  
    const dy = touch1.clientY - touch2.clientY;  
    return Math.sqrt(dx * dx + dy * dy);  
  },

})
